<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/vaadin-material-theme/vaadin-combo-box.html">
<link rel="import" href="../../bower_components/vaadin-material-theme/vaadin-grid.html">
<link rel="import" href="../view-app.html">
<link rel="import" href="../style/shared-styles.html">
<link rel="import" href="redux-mixin.html">
<dom-module id="view-setup-product">
  <template>
    <style include="shared-styles">
      :host {
        margin: 10px;
        height: 100%;
        display: block;
      }

      .btn {
        margin: 20px 5px 0 5px;
        width: 250px;
      }

      .add-btn {
        margin: 10px 0 10px;
        width: 250px;
      }

      .btn-block {
        width: 100%;
      }

      .item {
        border-bottom: 1px solid #eee;
        padding: 10px;
      }

      .product-image {
        height: auto;
        width: 100px;
      }

      .image-cell {
        height: 100px;
        width: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .details {
        padding: 10px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        min-height: 70px;
      }

      [part~="cell"] {
        padding: 0;
      }

      .process-list,
      .part-list {
        height: 200px;
      }

      .part {
        margin: 10px;
        padding: 20px;
        border: 1px solid #eee;
        border-radius: 5px;
      }

      .part p {
        margin: 10px 0;
      }

      .part h1 {
        text-align: center;
      }

      .part-info-group {
        margin-bottom: auto;
      }

      .part-block {
        margin: 20px 0 0 0;
      }

      [part="content"] {
        padding: 20px 30px;
      }

      .title {
        margin: 10px 0 20px 0;
      }

      .btn {
        width: 244px;
      }

      .block-group {
        margin: 10px 0;
      }

      .delete-btn {
        float: right;
      }

      .grid-item {
        border-bottom: 1px solid #eee;
        padding: 10px;
        max-height: 100px;
        display: flex;
        justify-content: space-between;
      }

      .grid-item:hover {
        background-color: #eee;
      }

      .grid-child {
        flex: 1;
      }

      .btn-group {
        margin-top: 40px;
      }

      vaadin-grid#productTable {
        height: 700px;
        --vaadin-grid-body-cell: {
          height: 200px;
        }
      }

      .tab-title {
        color: #202020
      }

    </style>
    <firebase-auth app-name="smart-mes" id="auth" user="{{user}}"></firebase-auth>
    <firebase-document app-name="smart-mes" id="userData" path="/user/[[user.uid]]" data="{{k}}"></firebase-document>
    <firebase-query app-name="smart-mes" id="productQuery" path="/data/[[k.key]]/factoryData/product" order-by-child="name" data="{{productData}}"></firebase-query>
    <firebase-document app-name="smart-mes" id="editProductQuery" path="/data/[[k.key]]/factoryData/product/[[editKey]]" data="{{editProductData}}"></firebase-document>
    <firebase-query app-name="smart-mes" id="processQuery" path="/data/[[k.key]]/factoryData/station" order-by-child="st_number"
      data="{{processData}}"></firebase-query>
    <firebase-query app-name="smart-mes" id="inventoryQuery" path="/data/[[k.key]]/factoryData/inventory" order-by-child="name"
      data="{{inventoryData}}"></firebase-query>
    <app-localstorage-document key="app-lang" data="{{language}}"></app-localstorage-document>
    <ul class="app-grid">
      <li>
        <!-- Add product card!-->
        <div class="card" hidden="[[showAddProduct]]">
          <paper-tabs selected="{{addProductTabs}}">
            <paper-tab role="tab" name="product">
              <span class="tab-title">1 Product Information</span>
            </paper-tab>
            <paper-tab role="tab" name="part">
              <span class="tab-title">2 Parts & Process</span>
            </paper-tab>
            <paper-tab role="tab" name="process">
              <span class="tab-title">3 Product Summary</span>
            </paper-tab>
          </paper-tabs>
          <iron-pages selected="{{addProductTabs}}">
            <div>
              <h1 class="title">Product Information</h1>
              <paper-input tabindex="0" label="{{localize('product-name')}}*" id="productName" type="text" value="{{productName}}" required always-float-label></paper-input>
              <paper-input tabindex="1" label="{{localize('sku-code')}}*" id="productSKU" type="text" value="{{productSKU}}" required always-float-label></paper-input>
              <paper-input tabindex="2" label="{{localize('cost')}}" id="productCost" type="number" maxlength="9" error-message="number only"
                min="0" max="9999" step="0.01" value="{{productCost}}" auto-validate always-float-label></paper-input>
              <paper-input tabindex="3" label="Description" id="productDescription" type="text" maxlength="300" required always-float-label></paper-input>
              <paper-button on-click="openBrowseImageFile" class="btn">
                {{localize('browse-image')}}
                <input type="file" accept="image/*" name="file" id="uploadImageFile" on-change="_verifyUploadFile" class="inputfile" />
              </paper-button>
              <div class="btn-group center">
                <paper-button class="btn" on-click="openProductList">
                  {{localize('dismiss')}}
                </paper-button>
              </div>
            </div>
            <div>
              <h1 class="title">Parts and Process</h1>
              <div class="block-group">
                <h3>Part Information</h3>
                <paper-input label="{{localize('name')}}" id="partName" value="{{partName}}" type="text" always-float-label></paper-input>
                <paper-input label="{{localize('sku-code')}}" id="partSKU" value="{{partSKU}}" type="text" always-float-label></paper-input>
                <paper-input label="Part Dependency (SKU Code)" id="partDependency" type="text" value="{{partDependency}}" required
                  always-float-label></paper-input>
                <vaadin-combo-box tabindex="4" label="{{localize('raw-materials-required')}}" id="inventoryCode" items="[[inventoryData]]"
                  item-value-path="code" item-label-path="name" loading="[[!inventoryData]]" theme="always-float-label">
                  <template>
                    <paper-item>
                      <paper-item-body>
                        <div>[[item.name]]</div>
                      </paper-item-body>
                    </paper-item>
                  </template>
                </vaadin-combo-box>
                <paper-input tabindex="5" label="Raw material quantity" id="inventoryQuantity" type="number" allowed-pattern="^(0|[1-9]\d*)(\.\d+)?$"
                  required always-float-label></paper-input>
                <h3 class="btn-group">Part Process</h3>
                <vaadin-combo-box label="{{localize('process-number')}}" id="processNumber" items="[[processData]]" name="Process selector"
                  item-label-path="st_number" item-value-path="st_number" value="{{selectedProcess}}" error-message="Invalid input"
                  loading="[[!processData]]" required always-float-label='true'>
                  <template>
                    <paper-item>
                      <paper-item-body three-line style="min-height: 0">
                        <div style="text-transform: capitalize">{{localize('process-name')}}: [[item.st_name]]</div>
                        <div secondary>{{localize('process-number')}}: [[item.st_number]]</div>
                        <div secondary>[[item.st_machine.length]] {{localize('machine')}}</div>
                      </paper-item-body>
                    </paper-item>
                  </template>
                </vaadin-combo-box>
                <paper-input label="Process Cycle Time (second)" id="processCycle" value="{{processCycle}}" type="number" maxlength="9" error-message="Number only"
                  min="0" max="[[maxInput]]" step="0.01" auto-validate always-float-label></paper-input>
                <paper-input label="Process Setup Time (second)" id="processSetup" value="{{processSetup}}" type="number" maxlength="9" error-message="Number only"
                  min="0" max="[[maxInput]]" step="0.01" auto-validate always-float-label></paper-input>
                <paper-button class="add-btn" on-click="addProcessToPart">
                  Add Process
                </paper-button>
                <p>Process Limit [[partProcess.length]] / [[maxProcess]]</p>
                <div class="frame">
                  <div class="process-list">
                    <iron-list items="[[processBundle]]" as="item">
                      <template>
                        <div tabindex$="[[tabIndex]]" class="grid-item">
                          <div class="grid-child">
                            <p>
                              <strong>{{localize('process-number')}} [[item.process]]</strong>
                            </p>
                            <p>{{localize('cycle-time')}} [[item.cycle]] {{localize('second')}}</p>
                            <p>{{localize('setup-time')}} [[item.setup]] {{localize('second')}}</p>
                          </div>
                          <div class="grid-child">
                            <paper-icon-button class="delete-btn" on-click="removeProcessFromPart" icon="vaadin:close-small" title="Delete"></paper-icon-button>
                          </div>
                        </div>
                      </template>
                    </iron-list>
                  </div>
                </div>
                <div class="center">
                  <paper-button class="btn" dialog-confirm on-click="addPartToProduct">
                    {{localize('add-part')}}
                  </paper-button>
                  <paper-button class="btn" on-click="clearPartFromProduct">
                    {{localize('clear')}}
                  </paper-button>
                </div>
              </div>
              <h3 class="btn-group center">Product Parts Summary</h3>
              <div class="part-block">
                <ul class="flex-container wrap">
                  <template is="dom-repeat" items="[[productPart]]" as="part">
                    <li class="flex-item">
                      <div class="part">
                        <div class="part-info-group">
                          <h2 class="title">[[part.name]]</h2>
                          <p>Part dependency: [[part.part_dependency]]</p>
                          <p>{{localize('sku-code')}}: [[part.sku]]</p>
                          <div class="frame part-list">
                            <iron-list items="[[getPartBundle(part.process, part.cycle, part.setup)]]" as="item">
                              <template>
                                <div tabindex$="[[tabIndex]]" class="item">
                                  <p>
                                    <strong>{{localize('process-number')}} [[item.process]]</strong>
                                  </p>
                                  <p>{{localize('cycle-time')}} [[item.cycle]] {{localize('second')}}</p>
                                  <p>{{localize('setup-time')}} [[item.setup]] {{localize('second')}}</p>
                                </div>
                              </template>
                            </iron-list>
                          </div>
                        </div>
                        <div class="center">
                          <paper-button class="thunderbird btn" on-click="removePartFromProduct">
                            {{localize('remove')}}
                          </paper-button>
                        </div>
                      </div>
                    </li>
                  </template>
                </ul>
              </div>
              <div class="btn-group center">
                <paper-button class="btn" on-click="openProductList">
                  {{localize('dismiss')}}
                </paper-button>
              </div>
            </div>
            <div>
              <h1 class="title">Product Summary</h1>
              <div class="block-group">
                <p>Product Name: [[productName]]</p>
                <p>Product SKU: [[productSKU]]</p>
                <p>Product Cost: [[productCost]]</p>
                <p>Product Part:</p>
              </div>
              <div class="part-block">
                <ul class="flex-container wrap">
                  <template is="dom-repeat" items="[[productPart]]" as="part">
                    <li class="flex-item">
                      <div class="part">
                        <div class="part-info-group">
                          <h2 class="title">[[part.name]]</h2>
                          <p>Part dependency: [[part.part_dependency]]</p>
                          <p>{{localize('sku-code')}}: [[part.sku]]</p>
                          <div class="part-list">
                            <iron-list items="[[getPartBundle(part.process, part.cycle, part.setup)]]" as="item">
                              <template>
                                <div tabindex$="[[tabIndex]]" class="item">
                                  <p>
                                    <strong>{{localize('process-number')}} [[item.process]]</strong>
                                  </p>
                                  <p>{{localize('cycle-time')}} [[item.cycle]] {{localize('second')}}</p>
                                  <p>{{localize('setup-time')}} [[item.setup]] {{localize('second')}}</p>
                                </div>
                              </template>
                            </iron-list>
                          </div>
                        </div>
                      </div>
                    </li>
                  </template>
                </ul>
              </div>
              <div class="btn-group center">
                <paper-button class="btn" on-click="openProductList">
                  {{localize('dismiss')}}
                </paper-button>
                <paper-button class="btn shamrock" on-click="addProduct">
                  {{localize('add')}}
                </paper-button>
              </div>
            </div>
          </iron-pages>
        </div>
      </li>

      <!-- Edit product card !-->
      <li>
        <div class="card" hidden="[[showEditProduct]]">
          <h1 class="title">{{localize('edit-product')}}</h1>
          <paper-input tabindex="0" label="{{localize('product-name')}}*" id="edit_ProductName" type="text" value="{{editProductData.name}}"
            required always-float-label></paper-input>
          <paper-input tabindex="1" label="{{localize('sku-code')}}*" id="edit_ProductSKU" type="text" value="{{editProductData.sku}}"
            required always-float-label></paper-input>
          <paper-input tabindex="2" label="{{localize('cost')}}" id="edit_ProductCost" type="number" maxlength="9" value="{{editProductData.cost}}"
            error-message="Number only" min="0" max="99999" step="0.01" auto-validate always-float-label></paper-input>
          <paper-input tabindex="3" label="Description" id="edit_ProductDescription" type="text" value="{{editProductData.description}}"
            required always-float-label></paper-input>
          <vaadin-combo-box tabindex="4" label="{{localize('raw-materials-required')}}" id="edit_InventoryCode" value="editProductData.inventory_code"
            items="[[inventoryData]]" item-value-path="code" item-value-path="code" item-label-path="name" loading="[[!inventoryData]]"
            theme="always-float-label">
            <template>
              <paper-item>
                <paper-item-body>
                  <div>[[item.name]]</div>
                </paper-item-body>
              </paper-item>
            </template>
          </vaadin-combo-box>
          <paper-input tabindex="5" label="Raw material quantity" id="edit_InventoryQuantity" type="number" allowed-pattern="^(0|[1-9]\d*)(\.\d+)?$"
            value="{{editProductData.inventory_use}}" required always-float-label></paper-input>
          <paper-button on-click="openBrowseImageFile" class="btn">
            {{localize('browse-image')}}
            <input type="file" accept="image/*" name="file" id="uploadImageFile" on-change="_verifyUploadFile" class="inputfile" />
          </paper-button>
          <paper-button class="btn" on-click="openAddPartDialog">
            {{localize('add-part')}}
          </paper-button>
          <paper-button class="btn" on-click="clearPartFromProduct">
            {{localize('clear')}}
          </paper-button>
          <div class="frame part-block">
            <ul class="flex-container wrap">
              <template is="dom-repeat" items="{{editProductData.part}}" as="part">
                <li class="flex-item">
                  <div class="part">
                    <div class="part-info-group">
                      <h2 class="title">[[part.name]]</h2>
                      <p>{{localize('sku-code')}}: [[part.sku]]</p>
                      <div class="frame part-list">
                        <iron-list items="[[getPartBundle(part.process, part.cycle, part.setup)]]" as="item">
                          <template>
                            <div tabindex$="[[tabIndex]]" class="item">
                              <p>
                                <strong>{{localize('process-number')}} [[item.process]]</strong>
                              </p>
                              <p>{{localize('cycle-time')}} [[item.cycle]] {{localize('second')}}</p>
                              <p>{{localize('setup-time')}} [[item.setup]] {{localize('second')}}</p>
                            </div>
                          </template>
                        </iron-list>

                      </div>
                    </div>
                    <div class="center">
                      <paper-button class="btn" on-click="openEditPartDialog" part="[[part]]">
                        {{localize('edit')}}
                      </paper-button>
                      <paper-button class="thunderbird btn" on-click="removePartFromProduct">
                        {{localize('remove')}}
                      </paper-button>
                    </div>
                  </div>
                </li>
              </template>
            </ul>
          </div>
          <div class="center">
            <paper-button class="btn" on-click="openProductList">
              {{localize('dismiss')}}
            </paper-button>
            <paper-button class="btn shamrock" on-click="saveProduct">
              {{localize('save')}}
            </paper-button>
          </div>
        </div>
        <!-- Show product management !-->
        <div class="card" hidden="[[showListProduct]]">
          <h1 class="title">{{localize('product-management')}}</h1>
          <vaadin-grid id="productTable" aria-label="Product Management" active-item="{{activeItem}}" selected-items="{{selectedItem}}"
            items="[[productData]]" size="10">
            <vaadin-grid-column flex="1">
              <template class="header">
                <div class="cell center">{{localize('image')}}</div>
              </template>
              <template>
                <div class="cell image-cell center">
                  <img class="product-image" src="[[item.image]]" alt="No Image">
                </div>
              </template>
            </vaadin-grid-column>

            <vaadin-grid-column flex="1">
              <template class="header">
                <div class="cell">{{localize('name')}}</div>
              </template>
              <template>
                <div class="cell">[[item.name]]</div>
              </template>
            </vaadin-grid-column>

            <vaadin-grid-column flex="1">
              <template class="header">
                <div class="cell">{{localize('sku-code')}}</div>
              </template>
              <template>
                <div class="cell">[[item.sku]]</div>
              </template>
            </vaadin-grid-column>

            <vaadin-grid-column flex="1">
              <template class="header">
                <div class="cell">{{localize('part')}}</div>
              </template>
              <template>
                <div class="cell">
                  <template is="dom-repeat" items="[[item.part]]" as="productPart">
                    <p>[[productPart.name]]</p>
                  </template>
                </div>
              </template>
            </vaadin-grid-column>

            <vaadin-grid-column flex="1">
              <template class="header">
                <div class="cell">{{localize('sku-code')}}</div>
              </template>
              <template>
                <div class="cell">
                  <template is="dom-repeat" items="[[item.part]]" as="productPart">
                    <p>[[productPart.sku]]</p>
                  </template>
                </div>
              </template>
            </vaadin-grid-column>

            <vaadin-grid-column flex="1">
              <template class="header">
                <div class="cell">Inventory Code</div>
              </template>
              <template>
                <div class="cell">
                  <p>[[item.inventory_code]]</p>
                </div>
              </template>
            </vaadin-grid-column>

            <vaadin-grid-column flex="1">
              <template class="header">
                <div class="cell">Inventory Require</div>
              </template>
              <template>
                <div class="cell">
                  <p>[[item.inventory_use]]</p>
                </div>
              </template>
            </vaadin-grid-column>

            <vaadin-grid-column flex="1">
              <template class="header">
                <div class="cell">{{localize('cost')}}</div>
              </template>
              <template>
                <div class="cell">[[item.cost]]</div>
              </template>
            </vaadin-grid-column>

            <vaadin-grid-column flex="0">
              <template class="header">
                <div class="cell">{{localize('detail')}}</div>
              </template>
              <template>
                <paper-checkbox aria-label$="Show Details for [[item.name]]" checked="{{detailsOpened}}"></paper-checkbox>
              </template>
            </vaadin-grid-column>

            <vaadin-grid-column flex="0">
              <template class="header">
                <div class="cell last">{{localize('edit')}}</div>
              </template>
              <template>
                <div class="cell last">
                  <paper-icon-button on-click="openEditProductCard" product="[[item]]" icon="vaadin:pencil" title="Edit"></paper-icon-button>
                </div>
              </template>
            </vaadin-grid-column>

            <vaadin-grid-column flex="0">
              <template class="header">
                <div class="cell last">{{localize('delete')}}</div>
              </template>
              <template>
                <div class="cell last">
                  <paper-icon-button on-click="removeProduct" product="[[item]]" icon="vaadin:trash" title="Delete"></paper-icon-button>
                </div>
              </template>
            </vaadin-grid-column>

            <!-- Row detail -->
            <template class="row-details">
              <div>
                <div class="details">
                  <div class="flex-item">
                    <h3>{{localize('part-name')}}</h3>
                    <template is="dom-repeat" items="[[item.part]]" as="productPart">
                      <p>[[productPart.name]]</p>
                    </template>
                  </div>
                  <div class="flex-item">
                    <h3>{{localize('process-sequence')}}</h3>
                    <template is="dom-repeat" items="[[item.part]]" as="productPart">
                      <p>[[getProductProcessSequence(productPart.process)]]</p>
                    </template>
                  </div>
                  <div class="flex-item">
                    <h3>Part Dependency</h3>
                    <template is="dom-repeat" items="[[item.part]]" as="productPart">
                      <p>[[productPart.dependency]]</p>
                    </template>
                  </div>
                  <div class="flex-item">
                    <h3>Description</h3>
                    <template>
                      <div class="cell">[[item.description]]</div>
                    </template>
                  </div>
                </div>
                <div class="details">
                  <div class="flex-item">
                    <h3>{{localize('setup-time')}} ({{localize('second')}})</h3>
                    <template is="dom-repeat" items="[[item.part]]" as="productPart">
                      <p>[[getProductProcessSequence(productPart.setup)]]</p>
                    </template>
                  </div>
                  <div class="flex-item">
                    <h3>Total Setup time ({{localize('second')}})</h3>
                    <template is="dom-repeat" items="[[item.part]]" as="productPart">
                      <p>[[getSumSetupTime(productPart.setup)]]</p>
                    </template>
                  </div>
                  <div class="flex-item">
                    <h3>{{localize('cycle-time')}} ({{localize('second')}})</h3>
                    <template is="dom-repeat" items="[[item.part]]" as="productPart">
                      <p>[[getProductProcessSequence(productPart.cycle)]]</p>
                    </template>
                  </div>
                  <div class="flex-item">
                    <h3>Total Cycle time ({{localize('second')}})</h3>
                    <template is="dom-repeat" items="[[item.part]]" as="productPart">
                      <p>[[getSumCycleTime(productPart.cycle)]]</p>
                    </template>
                  </div>
                </div>
              </div>
            </template>
          </vaadin-grid>
          <div class="center">
            <paper-button class="btn" on-click="openAddProductCard">
              {{localize('add-product')}}
            </paper-button>
          </div>
        </div>
      </li>
    </ul>

    <!-- ADD Part dialog !-->
    <flat-dialog id="addPartDialog" class="dialog" scroll-action="lock">
      <h1 class="title center">{{localize('add')}} {{localize('product-part')}}</h1>

      <div class="center">
        <paper-button class="btn" dialog-dismiss on-click="closeAddPartDialog">
          {{localize('dismiss')}}
        </paper-button>

      </div>
    </flat-dialog>

    <!-- Edit part dialog !-->
    <flat-dialog id="editPartDialog" class="dialog" scroll-action="lock">
      <h1 class="title center">{{localize('edit')}} {{localize('product-part')}}</h1>
      <div class="block-group">
        <paper-input label="{{localize('name')}}" id="partName" value="{{partName}}" type="text" required always-float-label></paper-input>
        <paper-input label="{{localize('sku-code')}}" id="partSKU" value="{{partSKU}}" type="text" required always-float-label></paper-input>
        <paper-input label="Part Dependency (Use SKU Code)" id="partDependency" value="{{partDependency}}" type="text" always-float-label></paper-input>
      </div>
      <div class="block-group">
        <!-- Add Process -->
        <h3>Process of Part</h3>
        <p>([[partProcess.length]] / [[maxProcess]])</p>
        <vaadin-combo-box label="{{localize('process-number')}}" id="processNumber" items="[[processData]]" name="Process selector"
          item-label-path="st_number" item-value-path="st_number" value="{{selectedProcess}}" error-message="Invalid input"
          loading="[[!processData]]" required always-float-label='true'>
          <template>
            <paper-item>
              <paper-item-body three-line style="min-height: 0">
                <div style="text-transform: capitalize">{{localize('process-name')}}: [[item.st_name]]</div>
                <div secondary>{{localize('process-number')}}: [[item.st_number]]</div>
                <div secondary>[[item.st_machine.length]] {{localize('machine')}}</div>
              </paper-item-body>
            </paper-item>
          </template>
        </vaadin-combo-box>
        <paper-input label="{{localize('cycle-time')}} ({{localize('second')}})" id="processCycle" value="{{processCycle}}" type="number"
          maxlength="9" error-message="Number only" min="0" max="[[maxInput]]" step="0.01" auto-validate always-float-label></paper-input>
        <paper-input label="{{localize('setup-time')}} ({{localize('second')}})" id="processSetup" value="{{processSetup}}" type="number"
          maxlength="9" error-message="Number only" min="0" max="[[maxInput]]" step="0.01" auto-validate always-float-label></paper-input>

        <paper-button class="add-btn" on-click="addProcessToPart">
          Add Process
        </paper-button>
      </div>
      <div class="frame">
        <div class="process-list">
          <iron-list items="[[processBundle]]" as="item">
            <template>
              <div tabindex$="[[tabIndex]]" class="grid-item">
                <p>
                  <strong>{{localize('process-number')}} [[item.process]]</strong>
                </p>
                <p>{{localize('cycle-time')}} [[item.cycle]] {{localize('second')}}</p>
                <p>{{localize('setup-time')}} [[item.setup]] {{localize('second')}}</p>
                <paper-icon-button class="delete-btn" on-click="removeProcessFromPart" icon="vaadin:close-small" title="Delete"></paper-icon-button>
              </div>
            </template>
          </iron-list>
        </div>
      </div>
      <div class="center">
        <paper-button class="btn" dialog-dismiss on-click="closeEditPartDialog">
          {{localize('dismiss')}}
        </paper-button>
        <paper-button class="btn" dialog-confirm autofocus on-click="addPartToProduct">
          {{localize('add-part')}}
        </paper-button>
      </div>
    </flat-dialog>

    <paper-toast id="toastAlert" always-on-top horizontal-align="right" text="{{toastText}}"></paper-toast>
  </template>
  <script>
    /**
     * @ViewSetupProduct
     * @polymer 
     * @extends {Polymer.Element}
     */
    class ViewSetupProduct extends ReduxMixin(Polymer.mixinBehaviors([Polymer.AppLocalizeBehavior], Polymer.Element)) {
      static get is() {
        return 'view-setup-product'
      }

      static get properties() {
        return {
          language: String,
          productData: {
            type: Object,
            notify: true
          },
          addProductTabs: {
            type: Number,
            value: 0
          },
          processData: Object,
          toastText: String,
          productKey: String,
          editKey: String,
          maxFiles: {
            type: Number,
            value: 1,
            readOnly: true
          },
          maxFileSize: {
            type: Number,
            value: 1000000
          },
          maxProcess: {
            type: Number,
            value: 12,
            readOnly: true
          },
          showListProduct: {
            type: Boolean,
            value: false
          },
          showAddProduct: {
            type: Boolean,
            value: true
          },
          showEditProduct: {
            type: Boolean,
            value: true
          },
          showAddPart: {
            type: Boolean,
            value: true
          },
          showEditPart: {
            type: Boolean,
            value: true
          },
          partProcess: {
            type: Array,
            notify: true,
            value: function () {
              return [];
            }
          },
          partProcessCycle: {
            type: Array,
            notify: true,
            value: function () {
              return [];
            }
          },
          partProcessSetup: {
            type: Array,
            notify: true,
            value: function () {
              return [];
            }
          },
          productPart: {
            type: Array,
            notify: true,
            value: () => {
              return []
            }
          },
          processBundle: {
            type: Object,
            notify: true
          }
        }
      }

      static get observer() {
        return ['getPartBundle(partProcess, partProcessCycle, partProcessSetup)']
      }

      static get actions() {
        return {
          add(data) {
            return {
              type: 'ADD_PART',
              productPart: data
            }
          },
          remove(data) {
            return {
              type: 'REMOVE_PART',
              index: data
            }
          },
          editCreate(data) {
            return {
              type: 'EDIT_SET_PART',
              editPart: data
            }
          },
          editAdd(data) {
            return {
              type: 'EDIT_ADD_PART',
              editPart: data
            }
          },
          editRemove(data) {
            return {
              type: 'EDIT_REMOVE_PART',
              index: data
            }
          },
          clear() {
            return {
              type: 'CLEAR_PART'
            }
          }
        }
      }

      connectedCallback() {
        super.connectedCallback()
        this.loadResources(this.resolveUrl('../../data/locales.json'))
      }

      // Add Process to Part
      addProcessToPart() {
        if (this.selectedProcess && this.processCycle) {
          // if found duplicate it will return index > -1
          let isDuplicated = this.partProcess.map(item => item).indexOf(this.selectedProcess) > -1
          if (this.partProcess.length < this.maxProcess) {
            if (isDuplicated) {
              window.alert('You already added this process')
              return
            }
            this.push('partProcess', this.selectedProcess)
            this.push('partProcessCycle', parseInt(this.processCycle) || 0)
            this.push('partProcessSetup', parseInt(this.processSetup) || 0)
            this.getPartBundle(this.partProcess, this.partProcessCycle, this.partProcessSetup)
            this.selectedProcess = null
            this.processCycle = null
            this.processSetup = null
          } else {
            window.alert(`Can't add more than ${this.maxProcess} processes per station`)
          }
        } else {
          window.alert('Please fill in process number, process cycle time and process setup time.')
        }
      }

      removeProcessFromPart(e) {
        let index = e.model.index;
        console.log("Selected index is " + e.model.index);
        console.log("Selected process is " + e.model.item);
        this.splice('partProcess', index, 1);
        this.splice('partProcessCycle', index, 1);
        this.splice('partProcessSetup', index, 1);
        this.getPartBundle(this.partProcess, this.partProcessCycle, this.partProcessSetup)
      }

      // Add Part to Product
      addPartToProduct() {
        const partObj = {
          name: this.partName,
          sku: this.partSKU,
          process: this.partProcess,
          cycle: this.partProcessCycle,
          setup: this.partProcessSetup,
          dependency: this.partDependency || 'none'
        };
        console.log(partObj)
        console.log(this.productPart)
        this.push('productPart', partObj)
        this.closeAddPartDialog();

      }

      removePartFromProduct(e) {
        if (window.confirm("Do you really want to delete this part?")) {
          let index = e.model.index;
          this.splice('productPart', index, 1)
        }
      }

      clearPartFromProduct(e) {
        if (window.confirm("Clear all product part?")) {
          this.splice('productPart', 0, this.productPart.length)
        }
      }

      // Add Product
      addProduct() {
        const productName = this.$.productName.value
        const productSKU = this.$.productSKU.value
        const timestamp = Math.round(Date.now() / 1000.0)
        const productColor = this.getRandomColor();
        let productPart = this.productPart
        let productCost = this.$.productCost.value || 0
        let productDescription = this.$.productDescription.value || 'N/A'
        let inventoryCode = this.$.inventoryCode.value || 'none'
        let inventoryQuantity = this.$.inventoryQuantity.value || 0
        let imageURL = "";
        productPart = productPart.splice(-1);
        if (productName && productSKU && productPart) {
          if (this.imageURL) {
            this._debouncer = Polymer.Debouncer.debounce(this._debouncer,
              Polymer.Async.timeOut.after(3000), () => {
                imageURL = this.imageURL;
                this._addProductToDatabase(timestamp, productCost, productName, productSKU,
                  inventoryCode, inventoryQuantity, productPart, productDescription,
                  productColor,
                  imageURL)
                this.toastText = 'Processing product.'
                this.$.toastAlert.open()
                this.openProductList()
              });
          } else {
            imageURL =
              "https://firebasestorage.googleapis.com/v0/b/smart-mes.appspot.com/o/default%2Fproduct%2Fstock-1.png?alt=media&token=6f83a0d2-5952-4e40-8a19-dbb51a8fbf37";
            this._addProductToDatabase(timestamp, productCost, productName, productSKU,
              inventoryCode,
              inventoryQuantity, productPart, productDescription,
              productColor, imageURL)
            this.openProductList()
          }
        } else {
          this.toastText = 'Please fill in the required field.'
          this.$.toastAlert.open()
        }
      }

      _addProductToDatabase(timestamp, productCost, productName, productSKU, inventoryCode, inventoryQuantity,
        productPart, productDescription, productColor, imageURL) {
        this.$.productQuery.ref.child(this.productKey).set({
          add: timestamp,
          cost: productCost,
          name: productName,
          sku: productSKU,
          image: imageURL,
          description: productDescription,
          color: productColor,
          inventory_code: inventoryCode,
          inventory_use: inventoryQuantity,
          part: productPart
        }).then(() => {
          this.openProductList()
          this.toastText = 'Add product successfully.'
          this.$.toastAlert.open()
        }).catch((error) => {
          this.toastText = 'Add Product failed.'
          this.$.toastAlert.open()
          console.error(error)
        })
      }

      _updateProduct(timestamp, productCost, productName, productSKU, inventoryCode, inventoryQuantity,
        productPart, productColor, imageURL) {
        this.$.productQuery.ref.child(this.productKey).update({
          add: timestamp,
          cost: productCost,
          name: productName,
          sku: productSKU,
          image: imageURL,
          color: productColor,
          inventory_code: inventoryCode,
          inventory_use: inventoryQuantity,
          part: productPart
        }).then(() => {
          this.openProductList();
          this.toastText = 'Update product successfully.'
          this.$.toastAlert.open()
        }).catch((error) => {
          this.toastText = 'Update Product failed.'
          this.$.toastAlert.open()
          console.error(error)
        })
      }

      saveProduct() {
        const productName = this.$.edit_ProductName.value
        const productSKU = this.$.edit_ProductSKU.value
        const processDependency = this.edit_ProcessDependency
        const timestamp = Math.round(Date.now() / 1000.0)
        const productColor = this.getRandomColor();
        let productPart = this.productPart
        let productCost = this.$.edit_ProductCost.value
        let inventoryCode = this.$.edit_InventoryCode.value
        let inventoryQuantity = this.$.edit_InventoryQuantity.value
        let imageURL = "";
        if (!productCost) productCost = 0;
        if (!inventoryCode) inventoryCode = "none";
        if (!inventoryQuantity) inventoryQuantity = 0;
        productPart = productPart.splice(-1);

        if (productName && productSKU && productPart && processDependency) {
          if (this.imageURL) {
            this._debouncer = Polymer.Debouncer.debounce(this._debouncer,
              Polymer.Async.timeOut.after(3000), () => {
                imageURL = this.imageURL;
                this._updateProduct(timestamp, productCost, productName, productSKU,
                  inventoryCode, inventoryQuantity, productPart,
                  productColor,
                  imageURL)
                this.toastText = 'Processing product.'
                this.$.toastAlert.open()
              });
            this.openProductList()
          } else {
            imageURL =
              "https://firebasestorage.googleapis.com/v0/b/smart-mes.appspot.com/o/default%2Fproduct%2Fstock-1.png?alt=media&token=6f83a0d2-5952-4e40-8a19-dbb51a8fbf37";
            this._updateProduct(timestamp, productCost, productName, productSKU, inventoryCode,
              inventoryQuantity, productPart, productColor, imageURL)
            this.openProductList()
          }
        } else {
          this.toastText = 'Please fill in the required field.'
          this.$.toastAlert.open()
        }
      }

      removeProduct(e) {
        if (window.confirm("Delete this product ?") == true) {
          const key = e.currentTarget.product.$key
          this.$.productQuery.ref.child(key).remove()
        }
      }

      _verifyUploadFile() {
        let file = this.$.uploadImageFile.files[0]
        if (!file.type.match(/image.*/)) {
          this.toastText = 'Invalid file format'
          this.$.toastAlert.open()
          this.$.uploadImageFile.value = null
        } else if (file.size > this.maxFileSize) {
          this.toastText = 'File size maximum is 1 MB'
          this.$.toastAlert.open()
          this.$.uploadImageFile.value = null
        } else {
          this.uploadProductImage(this.productKey)
        }
      }

      uploadProductImage(filename) {
        let file = this.$.uploadImageFile.files[0]

        if (file.type.match(/image.*/) && file.size < this.maxFileSize) {
          this.toastText = 'Uploading image'
          this.$.toastAlert.open()
          let uid = this.k.key
          let storageRef = this.$.auth.app.storage().ref()
          let metadata = {
            'contentType': file.type
          }
          let imagesRef = storageRef.child('factory/' + uid + '/product/' + filename)
          imagesRef.put(file, metadata)
            .then(snapshot => {
              let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
              // this.$.uploadProgress.value = progress
              this.$.uploadImageFile.files.uploading = true
              this.$.uploadImageFile.files.status = snapshot.state
              this.$.uploadImageFile.files.progress = progress
              this.$.uploadImageFile.files.loaded = snapshot.bytesTransferred
              this.$.uploadImageFile.files.size = snapshot.totalBytes
              let url = snapshot.metadata.downloadURLs[0]
              if (url) {
                this.imageURL = url;
                this.$.uploadImageFile.files.complete = true
                this.$.uploadImageFile.value = null
              }
            }).catch((error) => {
              this.$.uploadImageFile.files.error = error
              this.$.uploadImageFile.value = null
              console.error('Upload failed:', error)
            })
        } else {
          this.toastText = 'Error: Invalid file format'
          this.$.toastAlert.open()
          this.$.uploadImageFile.value = null
        }
      }

      getRandomColor() {
        const color = Math.floor(0x1000000 * Math.random()).toString(16);
        return '#' + ('000000' + color).slice(-6);
      }

      openBrowseImageFile() {
        this.$.uploadImageFile.click()
      }

      openAddPartDialog() {
        this.$.addPartDialog.opened = true
      }

      closeAddPartDialog() {
        this.$.addPartDialog.opened = false
      }

      closeEditPartDialog() {
        this.$.editPartDialog.opened = false
      }

      openAddProductCard() {
        this.showAddProduct = false
        this.showListProduct = true
        this.productKey = this.$.productQuery.ref.push().key
      }

      openProductList() {
        this.showAddProduct = true
        this.showEditProduct = true
        this.showListProduct = false
        this.editKey = ''
      }

      openEditProductCard(e) {
        this.showEditProduct = false
        this.showListProduct = true
        let key = e.currentTarget.product.$key
        this.editKey = key
      }

      openEditPartDialog(e) {
        this.$.editPartDialog.opened = true
      }

      getPartBundle(processArr, cycleArr, setupArr) {
        if (!processArr || !cycleArr || !setupArr) return
        const processObj = processArr.map((s, index, arr) => ({
          process: arr[index]
        }))
        const cycleObj = cycleArr.map((s, index, arr) => ({
          cycle: arr[index]
        }))
        const setupObj = setupArr.map((s, index, arr) => ({
          setup: arr[index]
        }))
        let mergeObj = []
        let i = 0
        while (i < processArr.length) {
          mergeObj.push(Object.assign(processObj[i], cycleObj[i], setupObj[i]))
          i++
        }
        this.processBundle = mergeObj;
        return mergeObj
      }

      getProductProcessSequence(arr) {
        if (!arr) return 'N/A'
        return arr.join(' → ')
      }

      getProcessNumber(processNumber) {
        if (!processNumber) return 1
        return processNumber + 1
      }

      getSumSetupTime(setup) {
        if (!setup) return 0
        let sumSetupTime = setup.reduce((a, b) => a + b); // apply sum function to all arr items to get sumSetup
        return sumSetupTime.toFixed(1)
      }

      getSumCycleTime(cycle) {
        if (!cycle) return 0
        let sumCycleTime = cycle.reduce((a, b) => a + b) // apply sum function to all arr items to get sumCycle
        return sumCycleTime.toFixed(1)
      }

      _clearField() {
        this.$.productName.value = ""
        this.$.productSKU.value = ""
        this.$.inventoryCode.value = ""
        this.$.inventoryQuantity.value = ""
        this.$.uploadImageFile.value = ""
      }

      _clearPartField() {
        this.partName = ""
        this.partSKU = ""
        this.partDependency = ""
      }
    }
    customElements.define(ViewSetupProduct.is, ViewSetupProduct)

  </script>
</dom-module>
